package com.tchhy.provider.net

import com.google.gson.Gson
import com.google.gson.JsonIOException
import com.google.gson.TypeAdapter
import com.google.gson.stream.JsonToken
import okhttp3.ResponseBody
import org.json.JSONException
import org.json.JSONObject
import retrofit2.Converter
import java.nio.charset.Charset

/**
 *
 * <p>
 * Author: wfy
 */
class BaseGsonResponseBodyConverter<T>(private val gson: Gson, val adapter: TypeAdapter<T>) :
    Converter<ResponseBody, T> {
    @Throws(JsonIOException::class)
    override fun convert(value: ResponseBody): T {
        value.use { value ->
            val jsonObject = JSONObject(value.source().readString(Charset.forName("UTF-8")))
            val jsonReader = gson.newJsonReader(jsonObject.toString().reader())
            val result = adapter.read(jsonReader)
            if (jsonReader.peek() != JsonToken.END_DOCUMENT) {
                throw JsonIOException("JSON document was not fully consumed.")
            }
            return result
        }
    }

}